package com.kfm.web.controller.order;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.kfm.common.domain.entity.Member;
import com.kfm.common.domain.entity.ShoppingCart;
import com.kfm.common.domain.response.Result;
import com.kfm.common.util.JwtUtils;
import com.kfm.order.service.ShoppingCartService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/cart")
@RestController
public class CartController {

    @Resource
    private ShoppingCartService service;

    @RequestMapping("/list")
    public Result list(HttpServletRequest request) throws JsonProcessingException {
        String token = request.getHeader("token");
        String subject = JwtUtils.getSubject(token);
        Member member = new JsonMapper().readValue(subject, Member.class);
        List<ShoppingCart> list = service.selectByMId(member.getId());
        return list == null ? Result.failure("查询失败") : Result.success("查询成功", list);
    }


    /**
     * 添加到购物车
     *
     * @param cart 添加的购物车信息
     * @return 响应内容
     */
    @RequestMapping("/add")
    public Result addCart(@RequestBody ShoppingCart cart, HttpServletRequest request) throws JsonProcessingException {
        String token = request.getHeader("token");
        String subject = JwtUtils.getSubject(token);
        Member member = new JsonMapper().readValue(subject, Member.class);
        cart.setMemberId(member.getId());
        int rows = service.insertSelective(cart);
        return rows > 0 ? Result.success("添加成功") : Result.failure("添加失败");
    }

/**
 * 修改购物车
 *
 * @param cart 修改的购物车信息
 * @return 响应内容
 */
@RequestMapping("/edit")
public Result updateCart(@RequestBody ShoppingCart cart) {
    int rows = service.updateByPrimaryKeySelective(cart);
    return rows > 0 ? Result.success("修改成功") : Result.failure("修改失败");
}


@DeleteMapping("/delete/{ids}")
public Result deleteMore(@PathVariable("ids") List<Integer> ids) {
    int rows = service.deleteMultipleElements(ids);
    return rows > 0 ? Result.success("删除成功") : Result.failure("删除失败");
}
}
